using AutoMapper;
using B.S.NewMedical.Api.Read.Application.Command.ContentManagement.Carousel;
using B.S.NewMedical.Api.Read.DTOS.Carousel;
using B.S.NewMedical.Domain.Hospital;
using B.S.NewMedical.ErrorCode;
using B.S.NewMedical.Infrastructure.Interface;
using MediatR;
using Microsoft.Extensions.Logging;
using System;
using System.Threading;
using System.Threading.Tasks;

namespace B.S.NewMedical.Api.Read.Application.Handler.ContentManagement.Carousel
{
    /// <summary>
    /// 根据ID获取轮播图处理器
    /// </summary>
    public class GetCarouselByIdHandler : IRequestHandler<GetCarouselByIdCommand, ApiResult<CarouselDto>>
    {
        private readonly IBaseRepository<CarouselModel> _carouselRepository;
        private readonly ILogger<GetCarouselByIdHandler> _logger;
        private readonly IMapper _mapper;

        public GetCarouselByIdHandler(
            IBaseRepository<CarouselModel> carouselRepository,
            ILogger<GetCarouselByIdHandler> logger,
            IMapper mapper)
        {
            _carouselRepository = carouselRepository;
            _logger = logger;
            _mapper = mapper;
        }

        public async Task<ApiResult<CarouselDto>> Handle(GetCarouselByIdCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始获取ID为{Id}的轮播图", request.Id);

                var carousel = await _carouselRepository.GetValue(request.Id);

                if (carousel == null || carousel.IsDeleted)
                {
                    _logger.LogWarning("轮播图ID {Id} 不存在或已被删除", request.Id);
                    return new ApiResult<CarouselDto>
                    {
                        Code = ApiEnum.Error,
                        Msg = "轮播图不存在"
                    };
                }

                var carouselDto = _mapper.Map<CarouselDto>(carousel);

                _logger.LogInformation("成功获取轮播图ID {Id}", request.Id);

                return new ApiResult<CarouselDto>
                {
                    Code = ApiEnum.Success,
                    Msg = "获取轮播图成功",
                    Data = carouselDto
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取轮播图ID {Id} 时发生异常", request.Id);
                return new ApiResult<CarouselDto>
                {
                    Code = ApiEnum.Error,
                    Msg = "获取轮播图失败：" + ex.Message
                };
            }
        }
    }
}